/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package web.app.client.security;

import web.app.client.ui.LoginView;

import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;

/**
 * 
 * @author michael
 */
public class AuthController extends Controller {

	protected LoginView view;

	public AuthController() {
		registerEventTypes(AuthEvents.AuthRequested);
		registerEventTypes(AuthEvents.AuthRequired);
		registerEventTypes(AuthEvents.AuthDenied, AuthEvents.AuthSuccess);
		view = new LoginView(this);
	}

	public void handleEvent(AppEvent event) {

		EventType t = event.getType();
		if (t == AuthEvents.AuthRequired) {
			showLogin();
		} else if (t == AuthEvents.AuthRequested) {
			onAuthRequested( event );
		} else {
			forwardToView(view, event);
		}

	}

	public void onAuthRequested(AppEvent event) {
		String userName = event.<String> getData(User.USERNAME);
		//String password = event.<String> getData(User.PASSWORD);

		// TODO: login impl

		User user = new User();
		user.name = userName;

		User.setCurrent( user );
		
		AppEvent e = new AppEvent(AuthEvents.AuthSuccess, user);
		Dispatcher.forwardEvent(e);
	}

	protected void showLogin() {
		view.show();
	}
}
